using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace MinesweeperGame
{
    /// <summary>
    /// 游戏统计类，管理游戏统计信息
    /// </summary>
    public class Statistics
    {
        /// <summary>
        /// 统计文件路径
        /// </summary>
        private const string STATS_FILE = "game_stats.txt";

        /// <summary>
        /// 游戏统计数据
        /// </summary>
        private Dictionary<Difficulty, DifficultyStats> difficultyStats;

        /// <summary>
        /// 演示统计数据
        /// </summary>
        private DemoStats demoStats;

        /// <summary>
        /// 构造函数
        /// </summary>
        public Statistics()
        {
            difficultyStats = new Dictionary<Difficulty, DifficultyStats>();
            demoStats = new DemoStats();

            // 初始化所有难度的统计
            foreach (Difficulty difficulty in Enum.GetValues(typeof(Difficulty)))
            {
                if (difficulty != Difficulty.Custom)
                {
                    difficultyStats[difficulty] = new DifficultyStats();
                }
            }

            LoadStats();
        }

        /// <summary>
        /// 记录游戏开始
        /// </summary>
        /// <param name="difficulty">游戏难度</param>
        public void RecordGameStarted(Difficulty difficulty)
        {
            if (difficulty == Difficulty.Custom) return;

            if (difficultyStats.ContainsKey(difficulty))
            {
                difficultyStats[difficulty].GamesPlayed++;
            }
        }

        /// <summary>
        /// 记录游戏胜利
        /// </summary>
        /// <param name="difficulty">游戏难度</param>
        /// <param name="time">完成时间（秒）</param>
        public void RecordGameWon(Difficulty difficulty, int time)
        {
            if (difficulty == Difficulty.Custom) return;

            if (difficultyStats.ContainsKey(difficulty))
            {
                var stats = difficultyStats[difficulty];
                stats.GamesWon++;
                stats.TotalTime += time;

                // 更新最佳时间
                if (stats.BestTime == 0 || time < stats.BestTime)
                {
                    stats.BestTime = time;
                }

                // 更新平均时间
                stats.AverageTime = stats.TotalTime / stats.GamesWon;
            }
        }

        /// <summary>
        /// 记录游戏失败
        /// </summary>
        /// <param name="difficulty">游戏难度</param>
        public void RecordGameLost(Difficulty difficulty)
        {
            if (difficulty == Difficulty.Custom) return;

            if (difficultyStats.ContainsKey(difficulty))
            {
                difficultyStats[difficulty].GamesLost++;
            }
        }

        /// <summary>
        /// 记录演示使用
        /// </summary>
        /// <param name="success">是否成功</param>
        /// <param name="time">演示时间（秒）</param>
        public void RecordDemoUsed(bool success, int time)
        {
            demoStats.DemoCount++;
            demoStats.TotalDemoTime += time;

            if (success)
            {
                demoStats.SuccessfulDemos++;
            }

            demoStats.AverageDemoTime = demoStats.TotalDemoTime / demoStats.DemoCount;
            demoStats.SuccessRate = (double)demoStats.SuccessfulDemos / demoStats.DemoCount * 100;
        }

        /// <summary>
        /// 获取难度统计
        /// </summary>
        /// <param name="difficulty">游戏难度</param>
        /// <returns>难度统计</returns>
        public DifficultyStats GetDifficultyStats(Difficulty difficulty)
        {
            if (difficultyStats.ContainsKey(difficulty))
            {
                return difficultyStats[difficulty];
            }
            return new DifficultyStats();
        }

        /// <summary>
        /// 获取演示统计
        /// </summary>
        /// <returns>演示统计</returns>
        public DemoStats GetDemoStats()
        {
            return demoStats;
        }

        /// <summary>
        /// 获取所有难度统计
        /// </summary>
        /// <returns>所有难度统计</returns>
        public Dictionary<Difficulty, DifficultyStats> GetAllDifficultyStats()
        {
            return new Dictionary<Difficulty, DifficultyStats>(difficultyStats);
        }

        /// <summary>
        /// 重置统计
        /// </summary>
        public void ResetStats()
        {
            foreach (var stats in difficultyStats.Values)
            {
                stats.Reset();
            }
            demoStats.Reset();
            SaveStats();
        }

        /// <summary>
        /// 保存统计到文件
        /// </summary>
        public void SaveStats()
        {
            try
            {
                var lines = new List<string>();
                lines.Add("# 扫雷游戏统计");
                lines.Add($"# 保存时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                lines.Add("");

                // 保存难度统计
                lines.Add("# 难度统计");
                foreach (var kvp in difficultyStats)
                {
                    var difficulty = kvp.Key;
                    var stats = kvp.Value;
                    lines.Add($"[{difficulty}]");
                    lines.Add($"GamesPlayed={stats.GamesPlayed}");
                    lines.Add($"GamesWon={stats.GamesWon}");
                    lines.Add($"GamesLost={stats.GamesLost}");
                    lines.Add($"BestTime={stats.BestTime}");
                    lines.Add($"AverageTime={stats.AverageTime}");
                    lines.Add($"WinRate={stats.WinRate:F2}");
                    lines.Add("");
                }

                // 保存演示统计
                lines.Add("# 演示统计");
                lines.Add($"DemoCount={demoStats.DemoCount}");
                lines.Add($"SuccessfulDemos={demoStats.SuccessfulDemos}");
                lines.Add($"TotalDemoTime={demoStats.TotalDemoTime}");
                lines.Add($"AverageDemoTime={demoStats.AverageDemoTime}");
                lines.Add($"SuccessRate={demoStats.SuccessRate:F2}");

                File.WriteAllLines(STATS_FILE, lines, Encoding.UTF8);
            }
            catch (Exception)
            {
                // 保存失败，忽略错误
            }
        }

        /// <summary>
        /// 从文件加载统计
        /// </summary>
        private void LoadStats()
        {
            try
            {
                if (!File.Exists(STATS_FILE)) return;

                var lines = File.ReadAllLines(STATS_FILE, Encoding.UTF8);
                Difficulty currentDifficulty = Difficulty.Beginner;

                foreach (var line in lines)
                {
                    var trimmedLine = line.Trim();
                    if (string.IsNullOrEmpty(trimmedLine) || trimmedLine.StartsWith("#"))
                        continue;

                    if (trimmedLine.StartsWith("[") && trimmedLine.EndsWith("]"))
                    {
                        var difficultyStr = trimmedLine.Substring(1, trimmedLine.Length - 2);
                        if (Enum.TryParse<Difficulty>(difficultyStr, out var difficulty))
                        {
                            currentDifficulty = difficulty;
                        }
                        continue;
                    }

                    var parts = trimmedLine.Split('=');
                    if (parts.Length != 2) continue;

                    var key = parts[0];
                    var value = parts[1];

                    if (difficultyStats.ContainsKey(currentDifficulty))
                    {
                        var stats = difficultyStats[currentDifficulty];
                        switch (key)
                        {
                            case "GamesPlayed":
                                if (int.TryParse(value, out int gamesPlayed))
                                    stats.GamesPlayed = gamesPlayed;
                                break;
                            case "GamesWon":
                                if (int.TryParse(value, out int gamesWon))
                                    stats.GamesWon = gamesWon;
                                break;
                            case "GamesLost":
                                if (int.TryParse(value, out int gamesLost))
                                    stats.GamesLost = gamesLost;
                                break;
                            case "BestTime":
                                if (int.TryParse(value, out int bestTime))
                                    stats.BestTime = bestTime;
                                break;
                            case "AverageTime":
                                if (int.TryParse(value, out int avgTime))
                                    stats.AverageTime = avgTime;
                                break;
                        }
                    }

                    // 处理演示统计
                    switch (key)
                    {
                        case "DemoCount":
                            if (int.TryParse(value, out int demoCount))
                                demoStats.DemoCount = demoCount;
                            break;
                        case "SuccessfulDemos":
                            if (int.TryParse(value, out int successfulDemos))
                                demoStats.SuccessfulDemos = successfulDemos;
                            break;
                        case "TotalDemoTime":
                            if (int.TryParse(value, out int totalDemoTime))
                                demoStats.TotalDemoTime = totalDemoTime;
                            break;
                        case "AverageDemoTime":
                            if (int.TryParse(value, out int avgDemoTime))
                                demoStats.AverageDemoTime = avgDemoTime;
                            break;
                        case "SuccessRate":
                            if (double.TryParse(value, out double successRate))
                                demoStats.SuccessRate = successRate;
                            break;
                    }
                }
            }
            catch (Exception)
            {
                // 加载失败，使用默认值
            }
        }

        /// <summary>
        /// 获取统计摘要
        /// </summary>
        /// <returns>统计摘要文本</returns>
        public string GetStatsSummary()
        {
            var summary = new StringBuilder();
            summary.AppendLine("=== 扫雷游戏统计摘要 ===");
            summary.AppendLine();

            // 难度统计
            summary.AppendLine("难度统计:");
            foreach (var kvp in difficultyStats)
            {
                var difficulty = kvp.Key;
                var stats = kvp.Value;
                summary.AppendLine($"  {difficulty}:");
                summary.AppendLine($"    游戏次数: {stats.GamesPlayed}");
                summary.AppendLine($"    胜利次数: {stats.GamesWon}");
                summary.AppendLine($"    失败次数: {stats.GamesLost}");
                summary.AppendLine($"    胜率: {stats.WinRate:F1}%");
                if (stats.BestTime > 0)
                {
                    summary.AppendLine($"    最佳时间: {FormatTime(stats.BestTime)}");
                }
                if (stats.AverageTime > 0)
                {
                    summary.AppendLine($"    平均时间: {FormatTime(stats.AverageTime)}");
                }
                summary.AppendLine();
            }

            // 演示统计
            summary.AppendLine("演示统计:");
            summary.AppendLine($"  演示次数: {demoStats.DemoCount}");
            summary.AppendLine($"  成功次数: {demoStats.SuccessfulDemos}");
            summary.AppendLine($"  成功率: {demoStats.SuccessRate:F1}%");
            if (demoStats.AverageDemoTime > 0)
            {
                summary.AppendLine($"  平均演示时间: {FormatTime(demoStats.AverageDemoTime)}");
            }

            return summary.ToString();
        }

        /// <summary>
        /// 格式化时间显示
        /// </summary>
        /// <param name="seconds">秒数</param>
        /// <returns>格式化的时间字符串</returns>
        private string FormatTime(int seconds)
        {
            int minutes = seconds / 60;
            int remainingSeconds = seconds % 60;
            return $"{minutes:D2}:{remainingSeconds:D2}";
        }
    }

    /// <summary>
    /// 难度统计类
    /// </summary>
    public class DifficultyStats
    {
        /// <summary>
        /// 游戏次数
        /// </summary>
        public int GamesPlayed { get; set; }

        /// <summary>
        /// 胜利次数
        /// </summary>
        public int GamesWon { get; set; }

        /// <summary>
        /// 失败次数
        /// </summary>
        public int GamesLost { get; set; }

        /// <summary>
        /// 最佳时间（秒）
        /// </summary>
        public int BestTime { get; set; }

        /// <summary>
        /// 平均时间（秒）
        /// </summary>
        public int AverageTime { get; set; }

        /// <summary>
        /// 总时间（秒）
        /// </summary>
        public int TotalTime { get; set; }

        /// <summary>
        /// 胜率
        /// </summary>
        public double WinRate
        {
            get
            {
                if (GamesPlayed == 0) return 0;
                return (double)GamesWon / GamesPlayed * 100;
            }
        }

        /// <summary>
        /// 重置统计
        /// </summary>
        public void Reset()
        {
            GamesPlayed = 0;
            GamesWon = 0;
            GamesLost = 0;
            BestTime = 0;
            AverageTime = 0;
            TotalTime = 0;
        }
    }

    /// <summary>
    /// 演示统计类
    /// </summary>
    public class DemoStats
    {
        /// <summary>
        /// 演示次数
        /// </summary>
        public int DemoCount { get; set; }

        /// <summary>
        /// 成功演示次数
        /// </summary>
        public int SuccessfulDemos { get; set; }

        /// <summary>
        /// 总演示时间（秒）
        /// </summary>
        public int TotalDemoTime { get; set; }

        /// <summary>
        /// 平均演示时间（秒）
        /// </summary>
        public int AverageDemoTime { get; set; }

        /// <summary>
        /// 成功率
        /// </summary>
        public double SuccessRate { get; set; }

        /// <summary>
        /// 重置统计
        /// </summary>
        public void Reset()
        {
            DemoCount = 0;
            SuccessfulDemos = 0;
            TotalDemoTime = 0;
            AverageDemoTime = 0;
            SuccessRate = 0;
        }
    }
} 